<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 新增弹框 -->
      <el-dialog
        title="编辑弹层"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialog"
      >
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click.native="hCancel">取消</el-button>
            <el-button size="small" type="primary" @click.native="hSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="roleList">
              <el-table-column label="序号" width="120" type="index" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success" @click="hAssignPermission(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="hEdit(row)">编辑</el-button>
                  <el-button size="small" type="danger" @click="hDel(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                :current-page="pageParams.page"
                :page-sizes="[2, 3, 5, 7]"
                :page-size="pageParams.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <el-dialog
        title="分配权限(一级为路由页面查看权限-二级为按钮操作权限)"
        :visible.sync="showDialogPer"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <assign-permission
          v-if="showDialogPer"
          :role-id="roleId"
          @close="showDialogPer=false"
        />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import assignPermission from './assignPermission'
import { getRoles, delRoles, addRole, updateRole } from '@/api/setting'
export default {
  components: {
    assignPermission
  },
  data() {
    return {
      roleId: '',
      showDialogPer: false, // 控制权限分配的显示和隐藏
      showDialog: false,
      roleForm: {
        name: '',
        description: ''
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      },
      pageParams: {
        page: 1,
        pagesize: 2
      },
      roleList: [],
      total: 0
    }
  },
  created() {
    this.loadRoles()
  },
  methods: {
    hAssignPermission(id) {
      // 记下来id
      this.roleId = id
      this.showDialogPer = true
    },
    async doEdit() {
      try {
        const res = await updateRole(this.roleForm)
        console.log(res)

        this.loadRoles()
        this.$message.success('编辑成功')
        this.showDialog = false
      } catch (err) {
        this.$message.error('编辑失败')
        console.log(err)
      }
    },
    hAdd() {
      this.showDialog = true
      this.isEdit = false
    },
    hEdit(row) {
      this.isEdit = true
      this.showDialog = true
      this.roleForm = row // 将传过来的数据填充到表单中
    },
    async doAdd() {
      try {
        const res = await addRole(this.roleForm)
        console.log(res)

        this.loadRoles()
        this.$message.success('添加成功')
        this.showDialog = false
        this.total++
        const maxPage = Math.ceil(this.total / this.pageParams.pagesize)
        this.pageParams.page = maxPage
      } catch (err) {
        this.$message.error('添加失败')
        console.log(err)
      }
    },
    async doDel(id) {
      try {
        const res = await delRoles(id)
        console.log(res, 'delRoles')
        // 刷新数据
        // page = 2 // 删除了最后一条数据
        // 如果当前页只有一条数据,应该让页码-1,page-1
        console.log(this.roleList, 'this.roleList')
        if (this.roleList.length === 1) {
          this.pageParams.page--
          if (this.pageParams <= 0) {
            this.pageParams.page = 1
          }
        }
        this.$message.success('删除成功')
        // 2. 重新请求
        this.loadRoles()
      } catch (err) {
        console.log(err)
        this.$message.error('删除失败')
      }
    },
    hDel(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(id)
      }).catch((err) => {
        console.log(err)
      })
    },
    async loadRoles() {
      try {
        const res = await getRoles(this.pageParams)
        console.log(res, 'getRoles')
        this.roleList = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageParams.page = 1
      this.pageParams.pagesize = val
      this.loadRoles()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pageParams.page = val
      this.loadRoles()
    },
    hSubmit() {
      console.log(111)
      this.$refs.roleForm.validate(valid => {
        if (!valid) return
        console.log(111)
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    hCancel() {
      this.showDialog = false
    }
  }
}
</script>
